import 'package:async/async.dart';
import 'package:boss/main.dart';
import 'package:boss/models/cloud_printer.dart';
import 'package:boss/models/commodity.dart';
import 'package:boss/models/printer_bill_style.dart';
import 'package:boss/models/store_area.dart';
import 'package:boss/ui/page/printer/constant/printer_constant.dart';
import 'package:boss/ui/page/printer/page/printerStepTwo/printer_step_two_page.dart';
import 'package:boss/ui/page/printer/printer_page.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:flutter/material.dart';
import 'package:hi_common/hi_common.dart';
import 'package:provider/provider.dart';

class CloudPrinterProvider extends ChangeNotifier {
  List<CloudPrinter> cloudPrinters = [];

  CloudPrinter editCloudPrinter;

  bool isEdit = false;

  Future<Result<List<CloudPrinter>>> queryCloudPrinterList() async {
    try {
      var res = await api.queryCloudPrinterList();
      if (!res.successful()) {
        return Result.error(res.msg);
      }
      cloudPrinters = res.data;

      return Result.value(res.data);
    } catch (e) {
      return Result.error(e.toString());
    }
  }

  setBrand(String brand) {
    editCloudPrinter.printerBrand = brand;
    notifyListeners();
  }

  setPageWidth(int paperWidth) {
    editCloudPrinter.paperWidth = paperWidth;
    notifyListeners();
  }

  nextStep() async {
    if (!checkStepOne()) return;

    try {
      showLoadingToast();

      var res = await api.registerCloudPrinter({
        'key': editCloudPrinter.cloudKey,
        'sn': editCloudPrinter.cloudSn,
        'paperWidth': editCloudPrinter.paperWidth,
        'printerBrand': editCloudPrinter.printerBrand,
        'printerName': editCloudPrinter.printerName,
      });
      if (!res.successful()) {
        toast(res.msg);
        return;
      }

      editCloudPrinter.id = res.data['id'];
      editCloudPrinter.connectModel = res.data['connectModel'];

      if (isEdit) {
        var find = cloudPrinters.firstWhere((item) => item.id == editCloudPrinter.printerDeviceId);
        find.printerName = editCloudPrinter.printerName;
        find.cloudKey = editCloudPrinter.cloudKey;
        find.cloudSn = editCloudPrinter.cloudSn;
        find.printerBrand = editCloudPrinter.printerBrand;
        find.paperWidth = editCloudPrinter.paperWidth;
      }

      isEdit ? Navigator.pop(GlobalPageContext.instance.context) : Navigator.pushNamed(GlobalPageContext.instance.context, PrinterStepTwoPage.pageName);
    } catch (e) {
      toast(e.toString());
    } finally {
      hideLoadingToast();
    }
  }

  bool checkStepOne() {
    if (!RegUtil.testNotEqEmpty(editCloudPrinter.printerName)) {
      toast('打印机名称不能为空');
      return false;
    }

    if (!RegUtil.testNotEqEmpty(editCloudPrinter.cloudSn)) {
      toast('打印机编号不能为空');
      return false;
    }

    var provider = Provider.of<CloudPrinterProvider>(
      GlobalPageContext.instance.context,
      listen: false,
    );
    if (provider.editCloudPrinter.printerBrand != PrinterConstant.SHANG_M_NAME) {
      if (!RegUtil.testNotEqEmpty(editCloudPrinter.cloudKey)) {
        toast('打印机密钥不能为空');

        return false;
      }
    }

    if (editCloudPrinter.printerBrand == null) {
      toast('请选择打印机品牌');
      return false;
    }

    if (editCloudPrinter.paperWidth == null) {
      toast('请选择打印机纸张宽度');
      return false;
    }

    return true;
  }

  setType(int type, List<PrinterBillStyle> styles) {
    editCloudPrinter.type = type;

    editCloudPrinter.printerPlanBillList = [];

    styles.forEach((item) {
      if (item.type == type && editCloudPrinter.printerPlanBillList.every((style) => style.billName != item.billName)) {
        editCloudPrinter.printerPlanBillList.add(PrinterPlanBillList.fromJson({
          'billName': item.billName,
          'count': 1,
          'type': type,
        }));
      }
    });

    notifyListeners();
  }

  setCommoditys(List<Commodity> commoditys) {
    editCloudPrinter.printerPlanFoodList = commoditys
        .map((item) => PrinterPlanFoodList.fromJson({
              'commodityId': item.id,
              'commodityName': item.title,
              'menuId': item.menuId,
              'menuName': item.menuName,
            }))
        .toList();

    notifyListeners();
  }

  setArea(List<StoreArea> areas) {
    editCloudPrinter.printerPlanAreaList = areas
        .map((item) => PrinterPlanAreaList.fromJson({
              'areaId': item.areaId,
              'areaName': item.areaName,
            }))
        .toList();
    notifyListeners();
  }

  setCutType(int cutType) {
    editCloudPrinter.cutType = cutType;
    notifyListeners();
  }

  setOrderByType(int type) {
    editCloudPrinter.orderByType = type;
    notifyListeners();
  }

  addCloudPrinter() async {
    try {
      showLoadingToast();

      var res = await api.addCloudPinter(editCloudPrinter);
      if (!res.successful()) {
        toast(res.msg);
        return;
      }

      toast('添加成功');
      cloudPrinters.add(editCloudPrinter);
      notifyListeners();

      Navigator.popUntil(GlobalPageContext.instance.context, ModalRoute.withName(PrinterPage.pageName));
    } catch (e) {
      toast(e.toString());
    } finally {
      hideLoadingToast();
    }
  }

  updateCloudPrinter() async {
    try {
      showLoadingToast();

      var res = await api.updateCloudPrinter(editCloudPrinter);
      if (!res.successful()) {
        toast(res.msg);
        return;
      }

      toast('修改成功');

      editCloudPrinter.id = editCloudPrinter.printerDeviceId;
      var index = cloudPrinters.indexWhere((item) => item.id == editCloudPrinter.printerDeviceId);
      cloudPrinters[index] = editCloudPrinter;
      notifyListeners();

      Navigator.popUntil(GlobalPageContext.instance.context, ModalRoute.withName(PrinterPage.pageName));
    } catch (e) {
      toast(e.toString());
    } finally {
      hideLoadingToast();
    }
  }

  setPrinterPlanBillList(List<PrinterPlanBillList> data) {
    editCloudPrinter.printerPlanBillList = data;
    notifyListeners();
  }

  deleteCloudPrinter(CloudPrinter printer) async {
    try {
      showLoadingToast();

      var res = await api.deleteCloudPrinter(printer.id);
      if (!res.successful()) {
        toast(res.msg);
        return;
      }

      toast('删除成功');

      cloudPrinters.remove(printer);
      notifyListeners();
    } catch (e) {
      toast(e.toString());
    } finally {
      hideLoadingToast();
    }
  }

  Future<Result<CloudPrinter>> getCloudPrinterById(int id) async {
    try {
      var res = await api.getCloudPrinterById(id);
      if (!res.successful()) {
        return Result.error(res.msg);
      }

      editCloudPrinter = res.data;

      return Result.value(res.data);
    } catch (e) {
      return Result.error(e.toString());
    }
  }
}
